package cn.ibizlab.core.authentication.config;

import com.google.code.kaptcha.text.TextProducer;
import com.google.code.kaptcha.util.Configurable;
import lombok.Data;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Random;

/**
 * 数值验证码生成器：生成指定位数的数字验证码
 */
@Data
public class DefaultDigitsCreator extends Configurable implements TextProducer {

    /**
     * 验证码长度
     */
    private int digits = 4;

    private static Random rand;

    public static Random getRand() {
        if (rand == null)
            try {
                //rand = SecureRandom.getInstanceStrong();
                rand = new Random();
            } catch (Exception e) {
                //rand = new Random();
                e.printStackTrace();
            }
        return rand;
    }

    /**
     * 获取验证码文本值
     * @return
     */
    public String getText() {
        if (digits <= 0)
            throw new IllegalArgumentException("The number of digits should be greater than 0.");

        int min = (int) Math.pow(10, digits-1);
        int max = (int) Math.pow(10, digits) - 1;
        return String.valueOf(getRand().nextInt(max - min + 1) + min);
    }

}